/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.ufrpe.bsi.manegedbean;
import br.ufrpe.bsi.bean.Log;
import br.ufrpe.bsi.bean.Usuario;
import br.ufrpe.bsi.dao.LogDAO;
import br.ufrpe.bsi.dao.UsuarioDAO;
import java.sql.SQLException;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Daniel
 */
public class LoginManegedBean {
    private UsuarioDAO usuarioDAO = new UsuarioDAO();
    private Usuario usuario = new Usuario();
    LogDAO logDAO = new LogDAO();
    
    public LoginManegedBean() {
    }

    public Usuario getUsuario() {
        return usuario;
    }

    public void setUsuario(Usuario usuario) {
        this.usuario = usuario;
    }
    
    public String logar(){
        try {
            usuario = usuarioDAO.retornar(usuario);
            Log log = new Log("Logar no sistema",usuario.getLogin());
            logDAO.inserir(log);
            FacesContext facesContext = FacesContext.getCurrentInstance(); 
            HttpServletRequest request = (HttpServletRequest) facesContext.getExternalContext().getRequest(); 
            HttpSession session = request.getSession();
            session.setAttribute("usuarioLogin", usuario.getLogin());
            facesContext.getExternalContext().getRequestMap().put("usuarioLogado", usuario);
            return "logado";
        } catch (Exception ex) {
            return "erro";
        }
    }
    
    public String logout() throws ClassNotFoundException, SQLException{
        try{
            Log log = new Log("Sair do sistema");
            logDAO.inserir(log);
            matarSessao();
            return "sairSessao";
        }catch(Exception ex){
            return "erroGeral";
        }
        
    }
    public static String recuperarLogin(){
        FacesContext facesContext = FacesContext.getCurrentInstance(); 
        HttpServletRequest request = (HttpServletRequest) facesContext.getExternalContext().getRequest(); 
        HttpSession session = request.getSession();
        return (String)session.getAttribute("usuarioLogin");
    }
    
    public static void matarSessao(){
        FacesContext facesContext = FacesContext.getCurrentInstance();  
        HttpSession session = (HttpSession) facesContext .getExternalContext().getSession(true);
        session.invalidate();
    } 
}
